<template>
    <el-dialog
        :title="!dataForm.id ? $t('handle.add') : show? $t('handle.update') : $t('handle.detail')"
        :close-on-click-modal="false"
        :visible.sync="visible">
    <div>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
      <el-form-item v-if="superAdmin==1" label="所属小区" prop="housingEstateId">
         <el-cascader ref="cascader" clearable style="width: 100%;" v-model="address" :options="options"  @click.native="getOne" @active-item-change="getNodes" :show-all-levels="true" :props="props">
         </el-cascader>
      </el-form-item>
      <el-form-item :label="$t('common.title')" prop="title">
        <el-input v-model="dataForm.title"
         placeholder="标题"></el-input>
      </el-form-item>
      <el-form-item label="跳转地址" prop="subTitle">
        <el-input v-model="dataForm.pathUrl"
         placeholder="跳转地址"></el-input>
      </el-form-item>
      <span ></span>
      <el-form-item label="所属模块" prop="type">
          <el-select style="width: 100%;" v-model="dataForm.type" filterable placeholder="请选择">
            <el-option v-for="item in dicts1" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="发布状态" prop="status">
          <el-select style="width: 100%;" v-model="dataForm.status" filterable placeholder="请选择">
            <el-option v-for="item in dicts" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="图片">
        <el-upload
          ref="upload"
          class="avatar-uploader"
          action="/clientauth/client/upload"
          :show-file-list="false"
          :on-error="handleError"
          :on-success="handleSucess"
          :headers="headers"
          :before-upload="beforeAvatarUpload">
          <img style="width: 80%;height:auto;" v-if="dataForm.picUrl" :src="this.imgUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <!-- <el-upload
          ref="upload"
          action="/clientauth/client/upload"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleSucess"
          :on-error="handleError"
          :on-exceed="handleExceed"
          :before-upload="beforeAvatarUpload"
          :file-list="fileList"
          :headers="headers"
          :limit="1"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，大小为750px x 279px的文件，且不超过2MB</div>
        </el-upload> -->
      </el-form-item>
      <el-form-item label="广告内容" prop="content">
        <ueditor :content="dataForm.content" v-if="true" ref="ueditor" @ueditorContent="getUeditorContent"> </ueditor>
        <!-- <el-input type="textarea"
        :rows="10"
        :maxlength = "500"
        v-model="dataForm.content" placeholder="广告内容(最长500字符)"></el-input> -->
      </el-form-item>
    </el-form>
    <div style="text-align:right;"></div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('handle.cancel') }}</el-button>
      <el-button v-if="show" type="primary" @click="dataFormSubmit()">{{ $t('handle.confirm') }}</el-button>
    </span>

    <!-- <ueditor v-if="true" ref="ueditor"></ueditor> -->
  </div>
  </el-dialog>
</template>
<script>
import Vue from "vue";
import ueditor from "@/components/ueditor";
import { dateFormate } from "@/utils/validate";
import { imgUrlHost } from "@/config/env";
import {
  getOne,
  getTwo,
  getThree,
  getFour,
  getFive,
  getSix
} from "@/utils/questUtils";
export default {
  data() {
    // 严格的验证规则可以放到这里验证
    let checkHousingEstate = (rule, value, callback) => {
      if (typeof this.address[this.address.length - 1] === "undefined") {
        callback(new Error("小区不能为空"));
      } else {
        callback();
      }
    };
    return {
      loading: "",
      imgUrl: "",
      imgUrlHost: imgUrlHost,
      addFlag: false,
      updateFlag: false,
      superAdmin: sessionStorage.getItem("superAdmin"),
      options: [{}],
      props: {
        value: "id",
        label: "name",
        children: "children"
      },
      address: [],
      headers: {
        Authorization: "Bearer " + Vue.cookie.get("access-token")
      },
      fileList: [{ url: "" }],
      picJson: { url: "" },
      dicts: [],
      dicts1: [],
      show: true,
      visible: false,
      imgSize: {}, // 图片的尺寸
      dataForm: {
        id: "",
        title: "",
        pathUrl: "",
        status: "",
        content: "",
        picUrl: "",
        type: "",
        housingEstateId: ""
      },
      // 验证Todo 其他的验证后续加上
      dataRule: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
        type: [{ required: true, message: "状态不能为空", trigger: "blur" }],
        housingEstateId: [
          { required: true, validator: checkHousingEstate, trigger: "blur" }
        ]
      }
    };
  },
  mounted() {},
  created() {
    // if (this.superAdmin == 1) {
    //   this.getOne();
    // }
  },
  // 引入的组件
  components: {
    ueditor
  },
  methods: {
    // 一级
    getOne() {
      getOne().then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options = response.data.page;
        }
      });
    },
    // 二级
    getTwo(countryId) {
      getTwo(countryId).then(response => {
        if (response.data.page && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map(item => {
            if (item.id === countryId) {
              item.children = response.data.page;
            }
          });
        }
      });
    },
    getThree(countryId, provinceId) {
      getThree(provinceId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((city, id) => {
                city.children = response.data.page;
              });
            }
          });
        }
      });
    },
    getFour(countryId, provinceId, cityId) {
      getFour(cityId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    city.children = response.data.page;
                  });
                }
              });
            }
          });
        }
      });
    },
    getFive(countryId, provinceId, cityId, areaId) {
      getFive(areaId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    if (city.id === cityId) {
                      city.children.map((area, aid) => {
                        area.children = response.data.page;
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    },
    getSix(countryId, provinceId, cityId, areaId, communityCodeId) {
      getSix(communityCodeId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            // this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    if (city.id === cityId) {
                      city.children.map((area, aid) => {
                        if (area.id === areaId) {
                          area.children.map((communt, ic) => {
                            communt.children = response.data.page;
                          });
                        }
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    },
    getNodes(val) {
      if (val.length === 1) {
        // 获取省
        this.getTwo(val[0]);
      } else if (val.length === 2) {
        // 市
        this.getThree(val[0], val[1]);
      } else if (val.length === 3) {
        // 区
        this.getFour(val[0], val[1], val[2]);
      } else if (val.length === 4) {
        this.getFive(val[0], val[1], val[2], val[3]); //社区
      } else if (val.length === 5) {
        this.getSix(val[0], val[1], val[2], val[3], val[4]); // 小区
      }
      //如果继续添加下级，类似这样继续添加即可
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {},
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {},
    // 文件上传成功时调用
    handleSucess(response, file, fileList) {
      this.$message({
        message: "文件上传成功",
        type: "success",
        duration: 1000,
        onClose: () => {
          this.imgUrl = imgUrlHost + response.iconName;
          this.dataForm.picUrl = response.iconName;
        }
      });
    },
    // 文件上传失败时调用
    handleError(err, file, fileList) {
      this.$message.error("文件上传失败");
    },
    handleExceed(files, fileList) {
      this.$message.error("只能上传一个文件,请先去除原文件");
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      let fileFlag = false;
      if (isJPG || isPNG) {
        fileFlag = true;
      } else {
        this.$message.error("上传头像图片只能是 JPG 格式或 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      if(this.dataForm.type == ''){
         this.$message.error('请先选择所属模块');
        return false;
      }
      // 首页轮播图限制
      let isSize = true;
      if(this.dataForm.type == '1'){
        let _this = this;
        let sizeArry = this.imgSize.homeAdSwiperSize.split('*');
        isSize = new Promise(function (resolve, reject) {
          let width = sizeArry[0];
          let height = sizeArry[1];
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function () {
            let valid = img.width == width && img.height == height;
            valid ? resolve() : reject();
          }
          img.src = _URL.createObjectURL(file);
        }).then(() => {
          return file;
        }, () => {
          _this.$message.error('图片尺寸限制为'+sizeArry[0]+' x '+ sizeArry[1]);
          return Promise.reject();
        });
      }
      return fileFlag && isLt2M && isSize;
    },
    // 富文本内容传递方法
    getUeditorContent(msg) {
      // this.dataForm.completeFlag = msg[0]
      this.dataForm.content = msg;
    },
    clearForm() {
      this.dataForm.title = "";
      this.dataForm.pathUrl = "";
      this.dataForm.status = "";
      this.dataForm.content = "";
      this.dataForm.picUrl = "";
      this.fileList[0].url = "";
      this.dataForm.type = "";
      this.address = [];
    },
    init(id, show, dicts, dicts1, imgSize) {
      this.imgSize = imgSize;
      this.fileList = [{ url: "" }];
      this.dicts = dicts;
      this.dicts1 = dicts1;
      this.show = show;
      this.visible = true;
      this.dataForm.id = id || 0;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
      });
      if (typeof id == "undefined") {
        // 新增
        this.clearForm();
      }
      if (this.dataForm.id) {
        this.updateFlag = true;
        this.addFlag = false;
        this.$http({
          url: `/dg-ic/ic/app-advertisement/info/${this.dataForm.id}`,
          method: "get",
          params: this.$http.adornParams()
        }).then(
          ({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.title = data.data.title;
              this.dataForm.pathUrl = data.data.pathUrl;
              this.dataForm.status = String(data.data.status);
              this.dataForm.content = data.data.content;
              this.dataForm.picUrl = data.data.picUrl;
              this.imgUrl = imgUrlHost + data.data.picUrl;
              this.fileList[0].url = imgUrlHost + data.data.picUrl;
              this.dataForm.type = String(data.data.type);
              this.options = [
                {
                  id: data.data.housingEstateId,
                  name: data.data.housingEstateName
                }
              ];
              this.address = [data.data.housingEstateId];
            } else {
              this.$message.error(data.msg);
            }
          },
          error => {
            if (error.response.status === 403) {
              this.$message.error("你没有权限");
            } else {
              this.$message.error("系统错误，请联系管理员");
            }
          }
        );
      }
    },
    // 表单提交
    dataFormSubmit() {
      this.dataForm.content = this.$refs.ueditor.getContent();
      this.$refs["dataForm"].validate(validate => {
        if (validate) {
          this.loading = true;
          this.$http({
            url: `/dg-ic/ic/app-advertisement/${
              !this.dataForm.id ? "save" : "update"
            }`,
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              title: this.dataForm.title,
              pathUrl: this.dataForm.pathUrl,
              status: this.dataForm.status,
              content: this.dataForm.content,
              picUrl: this.dataForm.picUrl,
              createBy: this.$store.state.user.id,
              updateBy: this.$store.state.user.id,
              // housingEstateId: sessionStorage.getItem("thiscommunityId") || "",
              housingEstateId:
                sessionStorage.getItem("superAdmin") == 1
                  ? this.address[this.address.length - 1]
                  : sessionStorage.getItem("thiscommunityId"), // 看是不是超管，时的话就给小区选择，否则就给他自身带的小区id
              type: this.dataForm.type
              // 后续的字段后续加上
            })
          }).then(
            ({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.loading = false;
                    this.visible = false;
                    this.$emit("refreshDataList");
                  }
                });
              } else {
                this.$message.error(data.msg);
                this.loading = false;
              }
            },
            error => {
              if (error.response.status === 403) {
                this.$message.error("你没有权限");
                this.loading = false;
              } else {
                this.$message.error("系统错误，请联系管理员");
                this.loading = false;
              }
            }
          );
        }
      });
    }
  }
};
</script>
